using System.Collections.Generic;
using System.Linq;
using UnityEngine.Events;

public class RedPointNote
{
    public readonly string name;                // 节点的名称

    public int redCount;                        // 自身的红点数量

    public int childRedCount;                   // 子结点的红点数量和 
    
    public readonly RedPointNote parentNote;    // 父节点 , 如果父节点为空, 那就是根节点 

    /// <summary>
    /// 子节点 <节点名称, 节点>
    /// </summary>
    public readonly Dictionary<string, RedPointNote> allChildNote = new Dictionary<string, RedPointNote>();

    public UnityAction<RedPointNote> callback;  // 绑定的回调函数

    public int RedCount => redCount + childRedCount;    // 所有的结点
    
    public RedPointNote(string name, RedPointNote parentNote)
    {
        this.name = name;
        this.parentNote = parentNote;
    }

    /// <summary>
    /// 删除结点
    /// </summary>
    /// <param name="noteName">节点名称</param>
    public void RemoteNote(string noteName)
    {
        if (allChildNote.ContainsKey(noteName))
        {
            allChildNote.Remove(noteName);
        }
    }

    /// <summary>
    /// 修改节点数量
    /// </summary>
    /// <param name="redCount"></param>
    public void ChangeRedCount(int redCount)
    {
        if (redCount == this.redCount) return;
        
        this.redCount = redCount;
        InvokeCallback();
    }
    
    /// <summary>
    /// 刷新红点树
    /// </summary>
    public void RefreshRedPoint()
    {
        // LINQ 表达式 : 重新计算子结点的红点数量
        var count = allChildNote.Values.Sum(note => note.RedCount);

        if (count == childRedCount) return;
        
        // 刷新数量, 并调用修改红点数量的回调函数
        childRedCount = count;
        InvokeCallback();
    }
    
    /// <summary>
    /// 强制执行回调函数
    /// </summary>
    public void InvokeCallback()
    {
        callback?.Invoke(this);
    }
}